import axios from "axios";
import router from '../router/router'

export function request(config) {
    const service = axios.create({
        baseURL: "http://192.168.43.213:83",
        timeout: 5000, // 请求超时时间
        // headers: {
        //     'Content-Type': 'application/x-www-form-urlencoded',
        //
        // }
    });

    //请求
    service.interceptors.request.use(config => {
            return config;
        },
        (error) => {
            console.log(error);
            return Promise.reject(error);
        });

    //响应
    service.interceptors.response.use(
        (response) => {
            const data = response.data;
            if (data.code == 200) {
                return Promise.resolve(data);
            } else if(data.code === 401){
                router.push({
                    name: 'Login'
                })
                return Promise.reject(null);
            }else {
                let err = {};
                if(data.msg){
                    let messInfo =  data.msg;
                    return Promise.reject(messInfo);
                }
                switch (data.code) {
                    case 400:
                        err.info = "请求无效";
                        break;

                    case 401:
                        err.info = "由于长时间未操作，登录已超时，请重新登录";
                        break;

                    case 403:
                        err.info = "服务器繁忙，请稍后再试，或联系管理员处理";
                        break;

                    case 404:
                        err.info = `请求地址出错`;
                        break;

                    case 405:
                        err.info = `未授权`;
                        break;

                    case 408:
                        err.info = "请求超时";
                        break;

                    case 500:
                        err.info = "服务器内部错误";
                        break;

                    case 501:
                        err.info = "服务未实现";
                        break;

                    case 502:
                        err.info = "网关错误";
                        break;

                    case 503:
                        err.info = "服务不可用";
                        break;

                    case 504:
                        err.info = "网关超时";
                        break;

                    case 505:
                        err.info = "HTTP版本不受支持";
                        break;

                    default:
                        err.info = "服务器繁忙，请稍后再试，或联系管理员处理";
                }
                let messInfo =  err.info;
                return Promise.reject(messInfo);
            }
        },
        (err) => {
            console.log("响应错误：" + err);
            return Promise.reject(err); //请求错误时，直接结束
        }
    );
    return service(config);
}
